﻿using System.Collections;
using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;

namespace Yoozoo.Gameplay.Liberty.StreetEvent
{
    public class CheckStreetMonsterHP : FlowControlNode
    {
        public BBParameter<int> sreetNpcId;
        public BBParameter<int> hp;

        private Coroutine _checkCor;
        
        protected override void RegisterPorts()
        {
            var caseTrue = AddFlowOutput("大于");
            var caseFalse = AddFlowOutput("小于等于");
            var caseThen = AddFlowOutput("Then");
            
            AddFlowInput("In", (f) =>
            {
                if (_checkCor!=null)
                {
                    StopCoroutine(_checkCor);
                }
                
                _checkCor = StartCoroutine(CheckHp(caseTrue,caseFalse,f));
                f.Call(caseThen);
            });
        }

        private IEnumerator CheckHp(FlowOutput caseTrue,FlowOutput caseFalse,Flow f)
        {
            bool ending = false;
            
            yield return new UnityEngine.WaitUntil(() =>
            {
                bool isTrue = false;
                var md = StreetEventManager.GetInstance("").GetMonster(sreetNpcId.value);
                if (md!=null)
                {
                    var aiEntity = LibertyAIUtils.GetNpc(md.uniqueId);
                    if (aiEntity != null)
                    {
                        isTrue = aiEntity.data.hp > hp.value;
                    }
                }

                if (isTrue)
                {
                    if (caseTrue.isConnected)
                    {
                        f.Call(caseTrue);
                        ending = true;
                    }
                }
                else
                {
                    if (caseFalse.isConnected)
                    {
                        f.Call(caseFalse);
                        ending = true;
                    }
                }
                
                
                return ending;
            });
            
           
        }

        public override void OnGraphStoped()
        {
            if (_checkCor!=null)
            {
                StopCoroutine(_checkCor);
            }
        }
    }
}